package org.javaboy.vhr.service;

import org.javaboy.vhr.mapper.HrMapper;
import org.javaboy.vhr.mapper.HrRoleMapper;
import org.javaboy.vhr.model.Hr;
import org.javaboy.vhr.util.HrUtil;
import org.javaboy.vhr.responseBean.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HrService implements UserDetailsService {

    @Autowired
    HrMapper hrMapper;
    @Autowired
    HrRoleMapper hrRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.getUserByUserName(username);
        if(null==hr){
            throw new UsernameNotFoundException("未找到此用户");
        }
        // 登录成功 set ROLS
        hr.setRoles(hrMapper.getHrRoleById(hr.getId()));
        return hr;
    }

    public List<Hr> getAllHr(String keywords) {
        return hrMapper.getAllHr(HrUtil.getCurrentHr().getId(),keywords);
    }

    public int updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    public ServerResponse updateHrRole(Integer hrId, Integer[] roleIds) {
        // 根据hrid删除hr_role信息
        hrRoleMapper.deleteByHrId(hrId);
        // 重新新增hr_role信息
        int result = hrRoleMapper.addHrRole(hrId,roleIds);
        if(result==roleIds.length){
            return ServerResponse.success("更新角色成功");
        }else {
            return ServerResponse.success("更新角色失败");
        }

    }

    /**
     * 删除hr
     * @param hrId
     * @return
     */
    public int deleteHr(Integer hrId) {
        return hrMapper.deleteByPrimaryKey(hrId);
    }
}
